package client

import (
	"log"
	"net/url"
	"wxp2p/common"

	"github.com/gorilla/websocket"
)

// 需要发送的信号放到这个chanel里，由websocket连接发送出去
var DebugLog = false
var P2PSignalSendChan = make(chan common.P2PSignal)
var P2PSignalRecvChan = make(chan common.P2PSignal)
var G_ClientType common.EClientType = common.EClientClient

func LinkSignalServer(addr string, user string) {
	u := url.URL{Scheme: "ws", Host: addr, Path: "/signal"}
	conn, _, err := websocket.DefaultDialer.Dial(u.String(), nil)
	if err != nil {
		log.Fatal("连接到信号服务器失败：", err)
	} else {
		log.Println("成功连接到信号服务器")
	}
	defer conn.Close()

	readdone := make(chan struct{})
	// 接收信号
	go func() {
		defer close(readdone)
		for {
			sig := common.P2PSignal{}
			err := conn.ReadJSON(&sig)
			if err != nil {
				log.Println("read signal from signal server error:", err)
				return
			}
			if DebugLog {
				log.Println("recv signal from server: ", sig)
			}
			if sig.SigType == common.EClientIdDublite {
				log.Println(sig.Content)
				break
			} else if sig.SigType == common.ENoServerClient {
				log.Println(sig.Content)
				break
			} else if sig.SigType == common.EBeginHole {
				go RunWebrtcOffer(sig.ClientId)
			} else {
				P2PSignalRecvChan <- sig
			}
		}
	}()
	// 发送信号
	senddone := make(chan struct{})
	go func() {
		defer close(senddone)
		for sig := range P2PSignalSendChan {
			sig.ClientType = G_ClientType
			err := conn.WriteJSON(sig)
			if err != nil {
				log.Println("send sig to server: error,", err)
				break
			}
			if DebugLog {
				log.Println("send sig to server:", sig)
			}
		}
	}()
	// 阻塞线程退出
	for {
		select {
		case <-readdone: //接收/发送消息出现错误，直接退出线程，或者【重新连接】
			log.Println("与信号服务器断开连接")
			return
		case <-senddone: //接收/发送消息出现错误，直接退出线程，或者【重新连接】
			log.Println("与信号服务器断开连接")
			return
		}
	}
}
